import React, { useCallback, useState, useEffect, useRef } from "react"
import { Select, Spin, TreeSelect } from "antd"
import { http, UdModal, UdModalForm } from "@/lib"
import apis from './../../../../../apis'
import UdSelect from "@/components/UdFormControls/UdSelect"
import { deepLoopFormateTree } from "@/utils/methods"
import { FormWrappedProps } from "antd/lib/form/interface"
import { WrappedFormUtils } from "antd/lib/form/Form"


const idx = 1
interface Props<T> {
  val: T
  areaCode: string | number
  list: any[]
  setVal: (list: any[]) => void
  brandCode: string
  delVal:any
  disabled?:boolean
}

type fn<T> = (props: Props<T>) => JSX.Element
const { Option } = Select

export const SelectInTable: fn<string | number> = ({
  val,
  setVal,
  areaCode,
  list,
  brandCode,
  delVal,
  disabled=true,
}: Props<string | number>) => {
  const [loading, setLoading] = useState(false)
  //下拉框数据集合
  const [dataList, setDataList] = useState([])
  //初始化下拉框数据
  useEffect(() => {
    setDataList(list)
  }, [list])
  const selectRef = useRef<any>()

  //获取焦点请求
  /* const getDataList = useCallback(
    () => {
      if (areaCode) {
        setLoading(true)
        http.get(apis.getSalesman, { params: { code: areaCode } }).then(res => {
          let data = res?.data?.map(({ id: code, name }) => ({ code, name })) || []
          setDataList(data)
          // handChange([val, undefined, data, label[0]], [TableColumnFiledMap.area, TableColumnFiledMap.connect, "concatList", "belongAreaName"], index)
        }).finally(() => setLoading(false))
      }
    },
    [areaCode],
  ) */

  /**
   * 弹框选择业务人员
   * 这里不能使用useCallback包裹，会存在某些场景弹框变更业务员操作更新tabelData，
   * 存在父组件BrandInfo里的tableData数据异常问题
   */
  const openModal = () => {
    // 弹框打开同时，让select失去焦点，不然反复触发onFocus方法
    selectRef.current && selectRef.current.blur()
    UdModal.open({
      title: '选择关联业务员',
      content: <ModalContentCm brandCode={brandCode} />,
      onOk: (values: any) => {
        const chosedPerson = values.chosedPerson || []
        setVal(
          chosedPerson.map((a: any) => ({
            salesmanId: +a.key,
            salesmanName: a.label,
          }))
        )

        // const personId = chosedPerson[0].key
        // const personName = chosedPerson[0].label
        // const dataList = chosedPerson.map(it => {
        //   let a = {
        //       code:it.key,
        //       name: it.label
        //     }
        //     return a
        // })
        // const dataList = [{ code: personId, name: personName }]
        // setVal(chosedPerson.map(it => ))

        // if (chosedPerson) {
        //   const personId = chosedPerson[0].key
        //   const personName = chosedPerson[0].label
        //   const dataList = chosedPerson.map(it => {
        //     let a = {
        //        code:it.key,
        //        name: it.label
        //      }
        //      return a
        //   })
        //   // const dataList = [{ code: personId, name: personName }]
        //   setVal(personId, personName, dataList)
        // }
      },
    })
  }
  return (
    <Select
      onFocus={openModal}
      ref={selectRef}
      value={val}
      mode="multiple"
      disabled={disabled}
      // onChange={(val, option) => {
      //   setVal(val, option.props.children, dataList)
      //   // handChange([val, option.props.children], [TableColumnFiledMap.connect, "businessPersonName"], index)
      // }}
      onDeselect={value => {
        delVal(value)
      }}
      placeholder="请选择关联业务员"
      loading={loading}
      notFoundContent={null}
    >
      {dataList.map((item, index) => (
        <Select.Option key={index} value={item.salesmanId}>
          {item.salesmanName}
        </Select.Option>
      ))}
    </Select>
  )
}

function ModalContentCm(props) {
  const { brandCode, ...rest } = props
  const [areaList, setAreaList] = useState([])
  const [businessList, setBusinessList] = useState([])
  const [querying, setQuerying] = useState(false)
  const [personArea, setPersonArea] = useState(props.personArea)
  const [businessPerson, setBusinessPerson] = useState(props.businessPerson)
  const [chosedPerson, setP] = useState([])
  const [ops, setOps] = useState([])

  let modalForm: WrappedFormUtils
  useEffect(() => {
    // debugger
    if (brandCode) {
      setQuerying(true)
      http.get(apis.getTreeByUserNew, { params: { organizationCode: brandCode } }).then(res => {
        let data = deepLoopFormateTree({ datas: res.data ? [res.data] : [], originKey: { value: 'code', title: 'name', children: 'children' } }) || []
        setAreaList(data)
      }).finally(() => setQuerying(false))
      // http.get(apis.getTreeByUser, { params: { organizationCode: brandCode } }).then(res => {
      //   // let data = res?.data?.children || []
      //   let data = deepLoopFormateTree({ datas: res.data ? [res.data] : [], originKey: { value: 'code', title: 'name', children: 'children' } }) || []
      //   setAreaList(data)
      // }).finally(() => setQuerying(false))
    }
  }, [brandCode])

  /* 根据片区获取业务员 */
  const getBusinessList = useCallback((areaCode) => {
    setPersonArea(areaCode)
    if (areaCode) {
      modalForm.setFieldsValue({ businessPerson: undefined }) // 重置关联业务员
      setQuerying(true)
      http.get(apis.getSalesman, { params: { code: areaCode } }).then(res => {
        let data =
          res?.data?.map(({ id: value, name: title, userCode, roleNames }) => ({
            value,
            title: userCode || roleNames ? `${title}(编号:${userCode},角色:${roleNames})` : title,
          })) || []
          setBusinessList(data)
      }).catch(() => {
        setBusinessList([])
      }).finally(() => setQuerying(false))
    }
  }, [modalForm])

  // useEffect(() => {
  //   getBusinessList(personArea)
  // }, [getBusinessList, personArea])


  const handleChange = useCallback((value) => {
    var compare = chosedPerson.some(it => Number(it.key) === value.key)
    if(!compare){
      chosedPerson.push({ key: (value.key).toString(), label: value.label })
      setP(chosedPerson)
    }
    // setBusinessPerson([value])
    modalForm.setFieldsValue({ businessPerson: [value] })
  }, [chosedPerson, modalForm])

  const onDeselect = (value) => {
    let result = chosedPerson.filter(item => item.key !== value.key)
    setP(result)

  }

  return (
    <Spin spinning={querying}>
      <UdModalForm {...rest} getForm={form => modalForm = form} items={[
        {
          label: '组织机构', id: 'personArea', render: () => {
            return (
              <UdTreeSelect
                onChange={getBusinessList}
                treeData={areaList}
                placeholder="请选择组织机构"
                showSearch={true}
                treeNodeFilterProp="title"
                dropdownStyle={{ maxHeight: 600 }}
              />
            )
          }
        },
        {
          label: '关联业务员', id: 'businessPerson', render: () => {
            return <UdSelect options={businessList} labelInValue placeholder="请选择关联业务员" showSearch={true} onChange={handleChange} />
          }
        },
        {
          label: '已关联业务员', id: 'chosedPerson', render: () => {
            return <UdSelect options={ops} labelInValue placeholder="请选择关联业务员" showSearch={true} mode="multiple"  onDeselect={onDeselect} />
          }
        },
      ]} values={{ personArea, businessPerson, chosedPerson }} />
    </Spin>
  )
}

function UdTreeSelect(props) {
  const { treeData, className, children, ...rest } = props
  return (
    <TreeSelect
      className={className}
      getPopupContainer={(triggerNode) => triggerNode}
      treeData={treeData}
      showCheckedStrategy={TreeSelect.SHOW_PARENT}
      {...rest}
    >
      {!treeData && props.children}
    </TreeSelect>
  )
}
